package com.bw.demo_mvi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MviActivity : AppCompatActivity() {
    private val mainViewModel by viewModels<MainViewModel>()
    private lateinit var tv: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mvi)
        tv = findViewById(R.id.tv)
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                mainViewModel.uiState.collect{
                    when (it){
                        is MainUIState.Loading -> tv.text = "正在加载"
                        is MainUIState.Success -> tv.text = "加载成功${it.data}"
                        is MainUIState.Error -> tv.text = "加载失败${it.error}"
                    }
                }
            }
        }
    }

    fun getVideo(view: View) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mainViewModel.channel.send(MainIntent.GetVideo(1,10))
            }
        }
    }
}